import { constObjs, isAuthorizedMap } from "@/const/const";
import { PermissionMap, User } from "@/interface/entity";

export const generateUser = (user: User): User => {
  const permissionList = (user.permissionString as string).split(",");
  // change permission
  // permissionList.forEach(permission => {
  //   user[permission as keyof PermissionMap] = "√";
  // });
  constObjs.permissionMapList.forEach(permission => {
    if (permissionList.includes(permission)) {
      user[permission as keyof PermissionMap] = "√";
    } else {
      user[permission as keyof PermissionMap] = "x";
    }
  });
  return user;
};

export const generateUserList = (userList: User[]): User[] => {
  userList.forEach(user => {
    user = generateUser(user);
  });
  return userList;
};

export const processUserBeforeToDb = (user: User): User => {
  // every user can change its userdata
  let permissionString = ",";

  // generate permissionString which will be stored in db
  Object.keys(user).forEach(key => {
    if (user[key as keyof User] == isAuthorizedMap.authorized) {
      permissionString += `${key},`;
    }
    // permission proporty will not be stored in db
    // (user[key as keyof User] as string | undefined) = undefined;
  });
  user.permissionString = permissionString;
  return user;
};
